<!DOCTYPE html>

<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>设备连接页面</title>
<link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<style>
	form *{
		padding:10px;
	}
	.row div {
		padding:10px;
	}
	
</style>
<body>
	<div class="container">
		<div class="row">
			<h3>设备连接页面</h3>
		 </div>
		 <div class="row">
		 	<div class="col-sm-12"><button class="btn btn-primary" onclick = "scan()">扫描周围设备</button></div>
		 	<div class="col-sm-12"><button class="btn btn-primary" onclick="stopScan()">停止扫描周围设备</button></div>
		 	<div class="col-sm-12"><button class="btn btn-primary" onclick="getInfo()">获取设备信息</button></div>
		 	<div class="col-sm-12"><button class="btn btn-primary"  onclick="bleConn()">连接</button></div>
		 	<div class="col-sm-12"><button class="btn btn-primary" onclick="sendData()">发送测试数据</button></div>
		 </div>
		 <p id='bindDevice'> </p>
		  <div class="row" style="display:none">
			  	<div class="row">TICKET:${jsapi_ticket}</div>
			 <div class="row">NONCE:${noncestr}</div>
			  <div class="row">TIMESTAMP:${timestamp}</div>
			  <div class="row">URL:${url}</div>
			  <div class="row">SIG:${signature}</div>
		  </div>
			<div class="row" id="lbInfo"></div>
	</div>
	
</body>
<script src="http://res.wx.qq.com/open/js/jweixin-1.2.0.js"></script>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<script>

var base64EncodeChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
function base64encode(str) {
    var out, i, len;
    var c1, c2, c3;
    len = str.length;
    i = 0;
    out = "";
    while (i < len) {
        c1 = str.charCodeAt(i++) & 0xff;
        if (i == len) {
            out += base64EncodeChars.charAt(c1 >> 2);
            out += base64EncodeChars.charAt((c1 & 0x3) << 4);
            out += "==";
            break;
        }
        c2 = str.charCodeAt(i++);
        if (i == len) {
            out += base64EncodeChars.charAt(c1 >> 2);
            out += base64EncodeChars.charAt(((c1 & 0x3) << 4)
                    | ((c2 & 0xF0) >> 4));
            out += base64EncodeChars.charAt((c2 & 0xF) << 2);
            out += "=";
            break;
        }
        c3 = str.charCodeAt(i++);
        out += base64EncodeChars.charAt(c1 >> 2);
        out += base64EncodeChars.charAt(((c1 & 0x3) << 4)
                | ((c2 & 0xF0) >> 4));
        out += base64EncodeChars.charAt(((c2 & 0xF) << 2)
                | ((c3 & 0xC0) >> 6));
        out += base64EncodeChars.charAt(c3 & 0x3F);
    }
    return out;
}
	!function(w){
		var deviceid = 'gh_643a4f52af73_92623e63af3db035';
		wx.config({
			  beta:true,
		    debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
		    appId: 'wxdb110e9fbff9b21d', // 必填，公众号的唯一标识
		    timestamp: '${timestamp}', // 必填，生成签名的时间戳
		    nonceStr: '${noncestr}', // 必填，生成签名的随机串
		    signature: '${signature}',// 必填，签名，见附录1
		    jsApiList: ['getNetworkType',
		                'openWXDeviceLib',
		                'closeWXDeviceLib',
		                'getWXDeviceInfos',
		                'sendDataToWXDevice',
		                'startScanWXDevice',
		                'stopScanWXDevice',
		                'connectWXDevice',
		                'disconnectWXDevice',
		                'getWXDeviceTicket',
		                'onWXDeviceBindStateChange',
		                'onWXDeviceStateChange',
		                'onReceiveDataFromWXDevice',
		                'onScanWXDeviceResult',
		                'onWXDeviceBluetoothStateChange',
		                'onWXDeviceLanStateChange',
		                ] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
		});
			
		wx.ready(function(){
			 wx.invoke('openWXDeviceLib', {
		            'brandUserName' : 'gh_643a4f52af73'  //公众号原始ID   IOS好像不需要要这一行代码
		        }, function(res) {
		            $("#lbInfo").append("<p>初始化设备库：" + res.err_msg + "</p>");
		            if (res.bluetoothState == "off") {
		                $("#lbInfo").append("<p>请先开启手机蓝牙</p>");
		            }else{
		            	alert(JSON.stringify(res));
		                wx.on('onScanWXDeviceResult', function(res) {
				            var macid = JSON.stringify(res.devices[0].deviceId).replace(/\"/g,"");
				            $("#lbInfo").append(macid);
				        });
				 
				        //手机蓝牙状态改变时触发 （这是监听事件的调用方法，注意，监听事件都没有参数）
				        wx.on('onWXDeviceBluetoothStateChange', function(res) {
				            //把res输出来看吧
				            $("#lbInfo").append("<p>蓝牙状态变更：" + JSON.stringify(res) + "</p>");
				        });
				 
				        //设备绑定状态改变事件（解绑成功，绑定成功的瞬间，会触发）
				        wx.on('onWXDeviceBindStateChange', function(res) {
				            $("#lbInfo").append("<p>绑定状态变更：" + res.err_msg + "</p>");
				        });
				 
				        //设备连接状态改变
				        wx.on('onWXDeviceStateChange', function(res) {
				            //有3个状态：connecting连接中,connected已连接,unconnected未连接
				            //每当手机和设备之间的状态改变的瞬间，会触发一次
				            alert(JSON.stringify(res))
				            $("#lbInfo").append("<p>设备连接状态：" + res.state + "</p>");
				        });
				 
				        //接收到设备传来的数据
				        wx.on('onReceiveDataFromWXDevice', function(res) {
				            $("#lbInfo").append("<p>收到设备数据：" + res.err_msg + "</p>");
				        });
				 
				        wx.error(function(res) {
				            alert("wx.error错误：" + JSON.stringify(res));
				            //如果初始化出错了会调用此方法，没什么特别要注意的
				        });
		            }
		            wx.invoke('getWXDeviceInfos', {
			            'connType' : 'ble'
			        }, function(res) {
			        	deviceid=res.deviceInfos[0].deviceId;
			        	
			            $("#lbInfo").append("<p>获取我的设备Id：" + deviceid + "</p>");
			        });
		        });
		 
		        w.scan =  function() {
		            wx.invoke("startScanWXDevice", {
		            	"connType":"blue",
		                "btVersion" : "bc"
		            }, function(res) {
		                alert(JSON.stringify(res))
		            });
		        }

		        w.stopScan = function () {
		            wx.invoke('stopScanWXDevice', {
		                'connType' : 'blue'
		            }, function(res) {
		                alert(JSON.stringify(res))
		            });
		        }

		        w.getInfo = function getInfo() {
		            wx.invoke('getWXDeviceInfos', {
		                'connType' : 'blue'
		            }, function(res) {
		            	$('#bindDevice').html(JSON.stringify(res));
		                alert(JSON.stringify(res))
		            });
		        }
		        //要修改这个设备ID,设备ID是申请获取的,需要与微信服务器一致
		        w.bleConn = function bleConn() {
		        	
		            wx.invoke('connectWXDevice', {
		                'deviceId' : deviceid,
		                'connType' : 'blue'
		            }, function(res) {
		                alert(JSON.stringify(res))
		            });
		        }

		        w.sendData = function sendData() {
		            wx.invoke('sendDataToWXDevice', {
		                'deviceId' : deviceid,
		                'connType' : 'blue',
		                'base64Data' : 'MDAwMEZGRjItMDAwMC0xMDAwLTgwMDAtMDA4MDVGOUIzNEZC'
		            }, function(res) {
		                alert(JSON.stringify(res))
		            });
		        }
		        
		    
		})
		wx.error(function(res){
			alert(res);
		});
	}(window);
	
</script>
</html>